/*
 * Copyright 2012-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.codestd.security.shiro.realm;

import com.codestd.security.mapper.SysRoleMapper;
import com.codestd.security.model.SysRole;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.PermissionResolver;
import org.apache.shiro.authz.permission.RolePermissionResolver;
import org.apache.shiro.authz.permission.WildcardPermissionResolver;
import org.springframework.beans.factory.InitializingBean;

import java.util.*;

/**
 * 通过角色获取权限
 *
 * @author Wang Chengwei(Jaune)
 * @since 1.0.0
 */
public class MemoryRolePermissionResolver implements RolePermissionResolver, InitializingBean {

    private PermissionResolver permissionResolver = new WildcardPermissionResolver();
    private SysRoleMapper sysRoleMapper;
    private Map<String, List<Permission>> rolePermissionsMapping = new HashMap<>();

    public void setSysRoleMapper(SysRoleMapper sysRoleMapper) {
        this.sysRoleMapper = sysRoleMapper;
    }

    @Override
    public Collection<Permission> resolvePermissionsInRole(String roleString) {
        return this.rolePermissionsMapping.get(roleString);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.resetMapping();
    }

    /**
     * 从数据库中读取权限资源对应关系
     */
    private void resetMapping() {
        List<SysRole> sysRoles = this.sysRoleMapper.findRolePermissionsMapping();
        for (SysRole sysRole : sysRoles) {
            List<Permission> permissions = this.rolePermissionsMapping.computeIfAbsent(sysRole.getRoleMark(),
                    o -> new ArrayList<>());
            permissions.add(this.permissionResolver.resolvePermission(sysRole.getPermissionMark()));
        }
    }

    /**
     * 提供一个refresh方法用户更新{@link #rolePermissionsMapping}中缓存的数据。
     */
    public void refresh() {
        this.resetMapping();
    }
}
